<?php

namespace app\commands;

use app\models\Log;
use Yii;
use yii\web\Controller;
use yii\filters\auth\CompositeAuth;
use yii\filters\auth\HttpBearerAuth;
use yii\filters\auth\QueryParamAuth;

/**
 * ArchivesController implements the CRUD actions for Archives model.
 */
class Service extends Controller
{

    // public $enableCsrfValidation = false;
    public $defaultRoute = 'statistics';

    public function init()
    {
        parent::init();
        // Yii::$app->user->enableSession = false;
        Yii::$app->user->enableAutoLogin = true;
    }

    public function behaviors()
    {
        $behaviors = parent::behaviors();
        $behaviors['authenticator'] = [
            'class' => CompositeAuth::className(),
            'authMethods' => [
                HttpBearerAuth::className(),
                QueryParamAuth::className(),
            ],
        ];
        return $behaviors;
    }

    private function validate_menu($route){
        if('all' == Yii::$app->user->identity->menus){
            return true;
        } else {
            if(is_array(Yii::$app->user->identity->menus) && Yii::$app->user->identity->menus[$route] != null){
                return true;
            }
        }
        return false;
    }

    public function beforeAction($action)
    {
        parent::beforeAction($action);

        if($this->validate_menu($action->controller->id . "/" . $action->id)){
            return $action;
        }
        
        echo '权限不够，请联系领导或系统管理员';
        exit;
    }

    private function insertPageLogToMysql($action)
    {
        $model = new Log();
        $model->user_id = Yii::$app->user->id;
        $model->menu_url = $action->controller->id . "/" . $action->id;
        $model->cip = Yii::$app->request->userIP;
        $model->createtime = date('Y-m-d H:i:s');
        $model->save();
    }

    public function afterAction($action, $result)
    {
        if (parent::afterAction($action, $result)) {
            $this->insertPageLogToMysql($action);
            return $result;
        } else {
            return false;
        }
    }
}